package com.atguigu.gmall.order.filter;

import com.atguigu.gmall.common.util.GmallThreadLocalUtils;
import com.atguigu.gmall.order.util.TokenUtil;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/***
 * 订单微服务自定义过滤器
 */
@WebFilter(filterName = "orderFilter",urlPatterns = "/*")
@Order(1)
public class OrderFilter extends GenericFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        //获取请求头中的令牌
        String token = request.getHeader("Authorization").replace("bearer ", "");

        //解析token
        Map<String, String> tokenMap = TokenUtil.dcodeToken(token);
        if(!tokenMap.isEmpty()){
            //获取token中的username
            String username = tokenMap.get("username");
            if(!StringUtils.isEmpty(username)){
                //将username存入本地线程
                GmallThreadLocalUtils.set(username);
            }
        }


        //放行
        filterChain.doFilter(request,servletResponse);
    }
}
